package com.ad.pet.app.login.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ad.pet.App;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.login.DaggerLoginComponet;
import com.ad.pet.app.login.MobileInputActivity;
import com.ad.pet.app.login.MobileInputContract;
import com.ad.pet.app.login.MobileInputPresenter;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.fragment.BaseFragment;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.User;
import com.ad.pet.ui.InputView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.umeng.socialize.UMShareAPI;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**邮箱登录
 * Created by SEELE on 2018/3/21.
 */

public class AccountLoginFragment extends BaseFragment implements AccountLoginContract.View,MobileInputContract.View {

    @Inject
    AccountLoginPresenter mPresenter;
    @BindView(R.id.input_account)
    InputView mInputAccount;
    @BindView(R.id.input_pwd)
    InputView mInputPwd;
    @BindView(R.id.btn_commit)
    Button mBtnCommit;
    @BindView(R.id.tv_forget)
    TextView mTvForget;
    @BindView(R.id.iv_pic_code)
    ImageView mIvPicCode;

//    @BindView(R.id.iv_weixin)
//    ImageView mIvWeixin;
//    @BindView(R.id.iv_facebook)
//    ImageView mIvFacebook;

//    @BindView(R.id.linear_line)
//    LinearLayout mLinearLine;

//    @BindView(R.id.linear_third)
//    LinearLayout mLinearThird;



    @Inject
    RxDisposable mRxDisposable;
    private boolean isAccount;
    private boolean isPwd;
    private boolean isEye;

    @Inject
    MobileInputPresenter mInputPresenter;
    ProgressDialog mProgressDialog;


//    boolean isFindPwd = true;


    private String mThirdType;
    private String mThirdValue;
    private String mThirdName;

    public final static int EMAIL_REQUEST=101;
    private UMShareAPI mMShareAPI;



    @Override
    protected void initData() {


    }

    @Override
    protected void initEvents() {
        mRxDisposable.add(RxTextView.textChanges(mInputAccount.getEtContent()).subscribe(new Action1<CharSequence>() {
            @Override
            public void call(CharSequence charSequence) {
                isAccount = charSequence.length() > 0;
                mBtnCommit.setEnabled(isAccount & isPwd);
            }
        }));
        mRxDisposable.add(RxTextView.textChanges(mInputPwd.getEtContent()).subscribe(new Action1<CharSequence>() {
            @Override
            public void call(CharSequence charSequence) {
                isPwd = charSequence.length() > 0;
                mBtnCommit.setEnabled(isAccount & isPwd);
            }
        }));

        mIvPicCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isEye = !isEye;
                setEye();
            }
        });



//        mTipsDialogView.setOnLotteryLinstener(new TipsDialogView.OnLotteryLinstener() {
//            @Override
//            public void onSure() {
//                if (TextUtils.isEmpty(mTipsDialogView.getEtEmail().getText().toString())) {
//                    ToastUtil.getToastUtil().showShort(mTipsDialogView.getEtEmail().getHint().toString());
//                    return;
//                }
//
//                if (TextUtils.isEmpty(mTipsDialogView.getEtPwd().getText().toString())) {
//                    ToastUtil.getToastUtil().showShort(mTipsDialogView.getEtPwd().getHint().toString());
//                    return;
//                }
//                if (TextUtils.isEmpty(mTipsDialogView.getEtCode().getText().toString())) {
//                    ToastUtil.getToastUtil().showShort(mTipsDialogView.getEtCode().getHint().toString());
//                    return;
//                }
//                if (mTipsDialogView.getEtPwd().getText().toString().length() < 6 || mTipsDialogView.getEtPwd().getText().toString().length() > 16) {
//                    ToastUtil.getToastUtil().showShort(getString(R.string.pwd_lengh_untrue));
//                    return;
//                }
////                if (mTipsDialogView.getEtCode().getText().toString().length() != 6) {
////                    ToastUtil.getToastUtil().showShort(getString(R.string.please_input_true_code));
////                    return;
////                }
//                mPresenter.forgetPwdReset(mInputEmailDialog.getEditText().getText().toString().trim(),mTipsDialogView.getEtEmail().getText().toString(),mTipsDialogView.getEtPwd().getText().toString().trim(),mTipsDialogView.getEtCode().getText().toString().trim());
////                mPresenter.setPwd("3", mTipsDialogView.getEtPwd().getText().toString(), "1", "1", "1", "1", mTipsDialogView.getEtEmail().getText().toString(), mTipsDialogView.getEtCode().getText().toString());
//            }
//        });


//        mIvWeixin.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                ((MobileInputActivity)getActivity()).toThirdLogin(1);
//                mThirdType= "wechat";
//                mMShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, authListener);
//            }
//        });
//        mIvFacebook.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mMShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.FACEBOOK, authListener);
////                mThirdValue = "250350589245699";
//                mThirdType="facebook";
////                mThirdName="刘毅祥";
////                mInputPresenter.checkBindThird(mThirdValue,"facebook");
//
//
//
//
//            }
//        });





    }

    @Override
    protected void initViews() {
//        mType = getArguments().getInt("type");
//        mThirdType = getArguments().getString(Constant.THIRD_PARTY);
//        mThirdValue = getArguments().getString(Constant.THIRD_VALUE);
//        mThirdName = getArguments().getString(Constant.THIRD_NAME);
        mTvForget.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        mTvForget.getPaint().setAntiAlias(true);//抗锯齿
        mProgressDialog = DialogUtil.createProgressDialog(getActivity());
        mPresenter.onCreate(this);

        mInputPresenter.onCreate(this);


        mMShareAPI = UMShareAPI.get(getActivity());


        setEye();


    }

    @Override
    public void initInjector() {
        DaggerLoginComponet.builder().applicationComponent(((MobileInputActivity) getActivity()).getApplicationComponent()).activityModule(((MobileInputActivity) getActivity()).getActivityModule()).build().inject(this);
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_account_login;
    }

    @Override
    protected BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void showLoading() {
        mProgressDialog.show();
    }

    @Override
    public void hideLoading() {
        mProgressDialog.dismiss();
    }

    @Override
    public void error(String msg) {
        ToastUtil.getToastUtil().showShort(msg);

    }



    @Override
    public void phoneLoginSuccess(User user) {

    }

    @Override
    public void accountLoginSuccess(User user) {
//        if (!TextUtils.isEmpty(mThirdType)){
//            RxBus.getDefault().post("third_bind_success");
//        }

        SpUtil.getInstance().putString(Constant.USER_ID,user.getUser_name());
        SpUtil.getInstance().putString(Constant.ACCESS_TOKEN,user.getToken());
        App.username = user.getUser_name();
        App.phone = user.getUser_tel();
        ToastUtil.getToastUtil().showShort(getString(R.string.login_success));
        RxBus.getDefault().post(new Events.AddCarts());
        RxBus.getDefault().post("set_message_number_success");
        getActivity().finish();

    }



    @Override
    public void getEmailCodeSuccess() {
//        mSubscriber = Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
//                .take(59)
//                .subscribe(new Action1<Long>() {
//                    @Override
//                    public void call(Long aLong) {
//                        isFindPwd = false;
//                        String format = String.format("%ds", 60 - aLong);
//                        RxTextView.text(mTipsDialogView.getBtnCode()).call(format);
//                    }
//
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//
//                    }
//                }, new Action0() {
//                    @Override
//                    public void call() {
//                        isFindPwd = true;
//                        RxTextView.text(mTipsDialogView.getBtnCode()).call(getString(R.string.get_phone_verify_code));
//
//                    }
//                });
//        mRxDisposable.add(mSubscriber);
    }

    @Override
    public void forgetPwdResetSuccess() {
        ToastUtil.getToastUtil().showShort(getString(R.string.reset_pwd_success));

    }

    @Override
    public void resetPwdSuccesss() {

    }

    @Override
    public void registJpushSuccess() {

    }


    @OnClick({R.id.btn_commit, R.id.tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_commit:
                String account = "";
                String psd = "";
                account = mInputAccount.getContent();

                psd = mInputPwd.getContent();

//                String thirdLoginValue = "";
//                if (TextUtils.isEmpty(mThirdType)){
//                    thirdLoginValue = "";
//                }else {
//                    ThirdPart thirdPart = new ThirdPart();
//                    thirdPart.setType(mThirdType);
//                    thirdPart.setData(new ThirdPartData(mThirdValue,mThirdName));
//                    thirdLoginValue = new Gson().toJson(thirdPart,ThirdPart.class);
//                }
                if (TextUtils.isEmpty(account)){
                    ToastUtil.getToastUtil().showShort(mInputAccount.getEtContent().getHint().toString());
                    return;
                }
                if (TextUtils.isEmpty(psd)){
                    ToastUtil.getToastUtil().showShort(mInputPwd.getEtContent().getHint().toString());
                    return;
                }
                mPresenter.accountLogin(account, psd);
                break;
            case R.id.tv_forget:
                Navigation.goForgetPwd(getActivity());
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRxDisposable != null)
            mRxDisposable.clear();
    }

    private void setEye() {

        if (isEye) {
            mIvPicCode.setImageResource(R.drawable.ic_eye);
            mInputPwd.getEtContent().setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mIvPicCode.setImageResource(R.drawable.ic_uneye);
            mInputPwd.getEtContent().setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

    }





    /**
     * 该方法用于转码让*号等字符能够被php识别
     * 让一些特殊字符能够成功的跟电脑端的匹配
     * 兼容pc端的老用户登录
     * \ " < ?  ` ' 空格 *
     *
     * @return
     */
    private String transCoding4OldSystemLogin(String string) {
        string = string.replaceAll("\\*", "%2A");
        return string;
    }

    @Override
    public void onDestroy() {
        if (mRxDisposable != null)
            mRxDisposable.clear();
        super.onDestroy();

    }

    @Override
    public void error(int code, String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {

            case EMAIL_REQUEST:
                getActivity().setResult(Activity.RESULT_OK, data);
                getActivity().finish();
                break;
        }
    }




    @Override
    public void checkPhoneSuccess(int isRegist) {

    }

    @Override
    public void checkBindThirdSuccess(User user) {

        if (!TextUtils.isEmpty(mThirdType)){
            RxBus.getDefault().post("third_bind_success");
        }
        RxBus.getDefault().post("set_message_number_success");
        SpUtil.getInstance().putString(Constant.ACCESS_TOKEN,user.getToken());
        ToastUtil.getToastUtil().showShort(getString(R.string.login_success));
        RxBus.getDefault().post(new Events.AddCarts());
//        Map loginMap = new HashMap();
//        loginMap.put("userid",  LyxUtils.md5(user.getAccess_token(), "e828854e53b93a3b1e19c4cab2de707a"));
//        MobclickAgent.onEvent(getActivity(), "__login", loginMap);
        getActivity().finish();
    }

    @Override
    public void checkBindUnBind() {
//        Navigation.goThirdBind(getActivity(),mThirdName,mThirdType);

    }

    @Override
    public void thirdLoginSuccess(User user) {

    }


}
